package com.whxy02.tolearn.app.utils;

import com.whxy02.tolearn.app.resultObject.ResultState;
import org.springframework.stereotype.Component;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

@Component
public class Download {

    @Resource
    PackResult packResult;

    public Map<String,Object> download(HttpServletResponse response, String prefix, String filename) throws IOException {

        byte[] buffer=new byte[1024];
        File file=new File("src\\main\\resources\\static"+prefix+"\\"+filename);

        String type = new MimetypesFileTypeMap().getContentType(filename);
        response.setContentType(type);
        response.setHeader("Content-Disposition","attachment;fileName="+filename);

        FileInputStream fis=null;
        BufferedInputStream bis=null;
        try{
            fis=new FileInputStream(file);
            bis=new BufferedInputStream(fis);
            OutputStream out=response.getOutputStream();
            int i=bis.read(buffer);
            while(i!=-1){
                out.write(buffer);
                i=bis.read(buffer);
            }
            return packResult.doPackToMap(ResultState.SUCCESS);
        }catch (Exception e){
            return packResult.doPackToMap(ResultState.DOWNLOAD_FIELD);
        }
        finally {
            bis.close();
            fis.close();
        }


    }

}
